package io.gitee.zhucan123.core.infrastructure.mvc;


import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;

/**
 * @author: zhuCan
 * @date: 2019/11/22 10:56
 * @description:
 */
public class ParamUtil {

  private ParamUtil() {
  }

  public static String keywordHandler(String keyword) {
    return "%" + StringUtils.defaultIfBlank(keyword, "").trim() + "%";
  }

  /**
   * http请求参数解析为Sort对象，例如：
   * <ul>
   *   <li>+id => order by id</li>
   *   <li>-createAt => order by createAt desc</li>
   *   <li>-createAt,-id => order by createAt desc, id desc</li>
   * </ul>
   * @param value
   * @return
   */
  public static Sort resolveSort(String value) {
    if (value == null || value.length() == 0) {
      return null;
    }
    Sort result = null;
    String[] orders = value.split(",");
    for (String order : orders) {
      order = order.trim();
      Sort sort;
      if (order.startsWith("-")) {
        sort = Sort.by(Sort.Direction.DESC, order.substring(1));
      } else if (order.startsWith("+")){
        sort = Sort.by(Sort.Direction.ASC, order.substring(1));
      } else {
        sort = Sort.by(Sort.Direction.ASC, order);
      }
      if (result == null) {
        result = sort;
      } else {
        result = result.and(sort);
      }
    }
    return result;
  }

}
